import 'package:citiesocial/_include.dart';
import 'package:citiesocial/widgets/goods/plus_minus.dart';
import 'package:citiesocial/ui/account/payment.dart';
import 'package:citiesocial/ui/account/my_orders.dart';

class MyCartList extends BaseStatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyCartListState();
}

class _MyCartListState extends BaseState<MyCartList> {
  CartEntity _cartEntity;

  ///是否是选择状态，给Offstage这个组件用的，false显示,true隐藏
  var _offstage = true;

  void _menuClick() {
    setState(() {
      _offstage = !_offstage;
    });
  }

  ///_offstage ? '前往结账' : '删除'
  void _cartOpera() {
    if (_offstage) {
      if ((_cartEntity?.list?.length ?? 0) > 0) {
        Navigator.push<String>(context,
                MaterialPageRoute(builder: (context) => Payment(_cartEntity)))
            .then((result) {
          if (result != null) {
            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => MyOrders()));
          } else {
            _loadData();
          }
        });
      } else {
        Toast.show(context, '购物车为空');
      }
    } else {
      String ids = '';
      if (_cartEntity != null &&
          _cartEntity.list != null &&
          _cartEntity.list.length > 0) {
        _cartEntity.list.forEach((goods) {
          if (goods.selectedMyState) {
            if (ids.length > 0) ids += ',';
            ids += goods.rec_id;
          }
        });
      }
      if (ids.length == 0) {
        Toast.show(context, '未选中任何商品');
      } else {
        LoadingDialog.show(context);
        HttpManager.deleteMoreCart(Configs.userId, Configs.userToken, ids)
            .then((yes) async {
          await LoadingDialog.dismiss(context);
          _loadData();
        });
      }
    }
  }

  void _loadData([bool showDialog = false]) {
    if (Configs.isLogined) {
      if (showDialog) LoadingDialog.show(context);
      HttpManager.cartList(Configs.userId, Configs.userToken, context: context)
          .then((cart) async {
        if (showDialog) LoadingDialog.dismiss(context);
        Configs.saveCartCount(cart?.list?.length ?? 0);
        setState(() {
          _cartEntity = cart;
        });
      });
    }
  }

  ///数字变化
  void _numberChange(GoodsEntity goods, bool increment) {
    if (increment) {
      LoadingDialog.show(context);
      HttpManager.addCart(Configs.userId, Configs.userToken, goods.goods_id)
          .then((yes) async {
        await LoadingDialog.dismiss(context);
        _loadData();
      });
    } else {
      LoadingDialog.show(context);
      HttpManager.reduceCart(Configs.userId, Configs.userToken, goods.rec_id)
          .then((yes) async {
        await LoadingDialog.dismiss(context);
        _loadData();
      });
    }
  }

  @override
  void initState() {
    Future.delayed(Configs.loadDelay, () {
      _loadData(true);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarUtils.normal(
        context,
        '购物车',
        GestureDetector(
          onTap: _menuClick,
          child: Container(
            padding: AppBarUtils.inner_image_padding,
            child: Center(
              child: Text(
                _offstage ? '编辑' : '取消',
                style: TextStyle(
                    color: Colors.grey, fontSize: AppBarUtils.menu_font_size),
              ),
            ),
          ),
        ),
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: !Configs.isLogined
            ? Align(
                alignment: Alignment.topCenter,
                child: NotLogin('登录查看购物车'),
              )
            : Column(
                children: <Widget>[
                  Container(
                    child: Text(
                      '总${_cartEntity?.total ?? '0'}元',
                      textAlign: TextAlign.left,
                      style: TextStyle(
                        fontSize: 15.0,
                      ),
                    ),
                    padding: EdgeInsets.all(15.0),
                  ),
                  Expanded(
                    child: DListView(
                      onRefresh: () async => _loadData(),
                      itemCount: _cartEntity?.list?.length ?? 0,
                      itemBuilder: (_, index) => GestureDetector(
                            onTap: () {
                              if (!_offstage) {
                                setState(() {
                                  _cartEntity.list[index].selectedMyState =
                                      !_cartEntity.list[index].selectedMyState;
                                });
                              }
                            },
                            child: Container(
                              child: Row(
                                children: <Widget>[
                                  Offstage(
                                    offstage: _offstage,
                                    child: Container(
                                      child: Image.asset(
                                        _cartEntity.list[index].selectedMyState
                                            ? 'imgs/js_cells_img_selected.png'
                                            : 'imgs/js_cells_img_not_selected.png',
                                        width: 20.0,
                                        height: 20.0,
                                        fit: BoxFit.cover,
                                      ),
                                      padding: EdgeInsets.all(5.0),
                                    ),
                                  ),
                                  Image(
                                    image: CachedNetworkImageProvider(
                                        '${_cartEntity.list[index].goods_img}'),
                                    width: 120.0,
                                    height: 120.0,
                                    fit: BoxFit.cover,
                                  ),
                                  Expanded(
                                    child: Container(
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          Text(
                                            '${_cartEntity.list[index].goods_brand}',
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                                fontSize: 13.0,
                                                color: Colors.grey),
                                          ),
                                          Text(
                                            '${_cartEntity.list[index].goods_name}',
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                                fontSize: 15.0,
                                                color: Colors.black),
                                          ),
                                          Text(
                                            '${_cartEntity.list[index].goods_price}',
                                            textAlign: TextAlign.left,
                                            style: TextStyle(
                                                fontSize: 14.0,
                                                color: Colors.grey),
                                          ),
                                          PlusMinus(
                                            count:
                                                '${_cartEntity.list[index].goods_number}',
                                            numberChange: (increment) =>
                                                _numberChange(
                                                    _cartEntity.list[index],
                                                    increment),
                                          ),
                                        ],
                                      ),
                                      margin: EdgeInsets.symmetric(
                                          horizontal: 10.0),
                                    ),
                                  ),
                                ],
                              ),
                              color: Colors.white,
                              margin: EdgeInsets.only(top: 1.0),
                            ),
                          ),
                    ),
                  ),
                  GestureDetector(
                    child: Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(15.0),
                      color: _offstage ? Configs.main : Colors.red,
                      child: Center(
                        child: Text(
                          _offstage ? '前往结账' : '删除',
                          style: TextStyle(fontSize: 18.0, color: Colors.white),
                        ),
                      ),
                    ),
                    onTap: _cartOpera,
                  ),
                ],
              ),
      ),
    );
  }
}
